package database

import (
	"hg/config"
	"hg/models"
	"hg/swagger"
	"strings"

	"github.com/sirupsen/logrus"
)

const (
	ColId = "id"
)

func InsertOneVideo(video *models.Videos) error {
	_, err := engine.InsertOne(video)
	return err
}

func GetVideoinfoById(videoId int) *swagger.Videos {
	video := &swagger.Videos{
		Id: videoId,
	}
	exist, err := engine.Table("video_object_view").Where("id = ?", videoId).Get(video)
	if err != nil {
		logrus.Error("serach video from db failed",err)
		return nil
	}
	if !exist {
		logrus.Error("video not exist")
		return nil
	}
	video.VideoUrl = getFullUrlByObjUrl(video.VideoUrl)
	video.CoverUrl = getFullUrlByObjUrl(video.CoverUrl)
	return video
}

func SearchVideo(searchRequest *models.SearchRequest) ([]*swagger.Videos, int, error) {
	var videos []*swagger.Videos
	//精确搜索
	session := engine.Table("video_object_view").Limit(searchRequest.Limit, searchRequest.Offset)
	if searchRequest.Acc {
		session = session.Where("title = ?", searchRequest.Name)
		//模糊搜索
	} else {
		session = session.Where("title like ?", "%"+searchRequest.Name+"%")
	}
	if searchRequest.OrderBy == "" {
		searchRequest.OrderBy = ColId
	}
	if searchRequest.Asc {
		session = session.Asc(searchRequest.OrderBy)
	} else {
		session = session.Desc(searchRequest.OrderBy)
	}

	cnt, err := session.FindAndCount(&videos)
	for _, video := range videos {
		video.VideoUrl = getFullUrlByObjUrl(video.VideoUrl)
		video.CoverUrl = getFullUrlByObjUrl(video.CoverUrl)
	}

	return videos, int(cnt), err
}

func getFullUrlByObjUrl(objUrl string) string {
	conf := config.GetConfig()
	result := strings.Split(objUrl, "/")
	fullUrl := "https://" + result[0] + "." + conf.Endpoint + "/" + result[1]
	return fullUrl
}
